﻿using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using RG.Common;

namespace RG.Common.WPF.Workplaces
{
    /// <summary>
    /// Interaction logic for MultiFrameWorkplace.xaml
    /// </summary>
    public partial class MultiFrameWorkplace : IView<MultiFrameWorkplaceVM>
    {
        // TODO Переделать нормальные команды
        public static readonly RoutedUICommand ToggleFrameDescCommand = new RoutedUICommand();

        public MultiFrameWorkplace()
        {
            InitializeComponent();
            BindCommands();
        }

        private void BindCommands()
        {
            ToggleFrameDescCommand.InputGestures.Add(new KeyGesture(Key.F11));
            CommandBindings.Add(new CommandBinding(ToggleFrameDescCommand, ExecutedCustomCommand));
        }

        public MultiFrameWorkplaceVM Presenter
        {
            get { return (MultiFrameWorkplaceVM)DataContext; }
            set { DataContext = value; }
        }

        private void MenuItem_OnClick(object sender, RoutedEventArgs e)
        {
            var mi = (MenuItem)e.OriginalSource;
            var itemVM = (FrameDescVM)mi.Header;
            Presenter.ShowNew(itemVM);
        }

        private void Close_Click(object sender, RoutedEventArgs e)
        {
            var t = (FrameworkElement) sender;
            Presenter.Close(t.Tag);
        }

        private void GridSplitter_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            leftColumn.Width = leftColumn.Width != new GridLength(7) ? new GridLength(7) : new GridLength(200);
        }


        public void ExecutedCustomCommand(object sender, ExecutedRoutedEventArgs e)
        {
            leftColumn.Width = leftColumn.Width != new GridLength(7) ? new GridLength(7) : new GridLength(200);
        }

        private void TreeView_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
        {
            if (e.NewValue == null) return;//почему то после прикручивания команд на контексное меню такое случается
            var itemVM = (FrameDescVM) e.NewValue;
            if (itemVM.Item is FrameSingle)
                Presenter.Show(itemVM);
            itemVM.IsSelected = false; // если вдруг умудрились попасть в итем, а не в его темплейт - убираем выделение
        }
    }
}
